package lab.exec;

import java.util.Random;
import java.util.Scanner;

import cn.flant.util.StringUtil;

public class Test {
	public static long sleep = 1;
	public static boolean print = false;
	public static int produce = 1;
	
	public static void main(String[] args) {
		String[] typeArray = new String[2];
		for (int i = 0; i < typeArray.length; i++) {
			typeArray[i] = String.valueOf(i);
		}
		int[] valueArray = new int[typeArray.length];
		ProcessorFactory factory = new DefaultProcessorFactory();
		final BalanceExecuteService<Integer> bes = new BalanceExecuteService<Integer>(20, factory);
		bes.setBalanceInterval(20000);
		bes.setQueueGapLimit(100);
		bes.startup();
		new Thread() {
			public void run() {
				Scanner scan = new Scanner(System.in);
				String line = null;
				while ((line = scan.nextLine()) != null) {
					int idx = line.indexOf("=");
					System.err.println("process command : " + line);
					if (idx > 0) {
						String key = line.substring(0, idx);
						String value = line.substring(idx + 1);
						if ("thread".equalsIgnoreCase(key)) {
							int threadSize = StringUtil.toInteger(value, bes.getThreadPoolSize());
							if (threadSize <= 0) {
								continue;
							}
							bes.setThreadPoolSize(threadSize);
						} else if ("sleep".equalsIgnoreCase(key)) {
							long time = StringUtil.toLong(value, sleep);
							if (time <= 0) {
								continue;
							}
							sleep = time;
						} else if ("speed".equalsIgnoreCase(key)) {
							int speed = StringUtil.toInteger(value);
							if (speed <= 0) {
								continue;
							}
							int time = 1000 / speed;
							produce = time == 0 ? 1 : time;
						} else if ("gap".equalsIgnoreCase(key)) {
							int gap = StringUtil.toInteger(value);
							if (gap <= 0) {
								continue;
							}
							bes.setQueueGapLimit(gap);
						}
					} else if ("print".equalsIgnoreCase(line)) {
						print = !print;
					} else if ("startup".equalsIgnoreCase(line)) {
						bes.startup();
					} else if ("shutdown".equalsIgnoreCase(line)) {
						bes.shutdown(false);
					}
				}
			}
		}.start();
		Random r = new Random();
		while (true) {
			int idx = r.nextInt(typeArray.length);
			String type = typeArray[idx];
			int max = valueArray[idx];
			valueArray[idx] = ++max;
			try {
				bes.submitObject(type, max);
			} catch (RejectedException e) {
			} catch (ProcessQueueException e) {
			}
			try {
				Thread.sleep(produce);
			} catch (InterruptedException e) {
			}
		}
	}

	static class DefaultProcessorFactory implements ProcessorFactory {
		public Processor newProcessor() {
			return new Processor() {
				public void process(Object obj) {
					if (print) {
						System.out.println(Thread.currentThread().getName() + ": proces done <" + obj + ">, then sleep<" + sleep + ">");
					}
					try {
						Thread.sleep(sleep);
					} catch (InterruptedException e) {
					}
				}
			};
		}
	}
}
